import java.security.PublicKey;

public class Transaction implements Cloneable{
    public String from; // 这里简化为交易双方的地址(公钥）
    public String to;
    public int amount; // 交易金额
    public byte[] signature; // 交易的签名

    public Transaction(String from, String to, int amount) throws Exception {
        this.from = from;
        this.to = to;
        this.amount = amount;
    }

    // 获取交易的哈希
    public String getTxHash(){
        return Utils.SHA256(from,to, String.valueOf(amount));
    }

    // 获取交易的签名
    public void sign(String sigKey) throws Exception {
        String msgToSign = this.toString();
        System.out.println("sigKey: "+sigKey);
        signature = ECCKeyGen.sign(sigKey, msgToSign);
    }

    // 验签名
    public boolean validate() throws Exception {
        if(this.from == "" || this.from == "出块交易无来源方"){ // 出块奖励的交易、创世交易
            return true;
        }
        String pubKeyStr = from;
        String message = this.toString();
        return ECCKeyGen.verify(pubKeyStr, message,signature);
    }

    @Override
    public String toString() {
        return "Transaction{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", amount=" + amount +
                '}';
    }

    @Override
    public Transaction clone() throws CloneNotSupportedException {
        return (Transaction) super.clone();
    }

    public String getFrom(){ // 发款方公钥
        return from;
    }
    public String getTo(){ // 收款方公钥
        return to;
    }
}
